package models

import "github.com/astaxie/beego/orm"

//GetTPatchOfAPP
func GetTPatchOfAPP(appid int64, enable, from, step int) (totalCount int64, ml []TPatch, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TPatch))

	qs = qs.Filter("t_app_id", appid)
	if enable == 0 {
		// 如果为 0 则只显示可用的。 如果为1 则显示所有。
		qs = qs.Filter("enable", 1)
	}
	totalCount, err = qs.Count()
	if err != nil {
		return 0, nil, err
	}
	_, err = qs.OrderBy("-id").Offset(from).Limit(step).All(&ml)
	return
}

//DeleteTPatchOfAPP
func DeleteTPatchOfAPP(appid int64) (err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TPatch))
	_, err = qs.Filter("t_app_id", appid).Delete()
	return
}

//KillTPatchOfAPP 只注销 app所属的，不删除
func KillTPatchOfAPP(t_app_id int64, enable int) (err error) {
	o := orm.NewOrm()
	tableName := new(TPatch).TableName()
	_, err = o.Raw("update "+tableName+" set enable = ? where t_app_id = ?", enable, t_app_id).Exec()
	return
}

//KillTPatch 只注销 patch ，不删除
func KillTPatch(patchid int64, enable int) (err error) {
	o := orm.NewOrm()
	tableName := new(TPatch).TableName()
	_, err = o.Raw("update "+tableName+" set enable = ? where id = ?", enable, patchid).Exec()
	return
}

type patchNumOfApp struct {
	AppId      int    `json:"app_id"`
	BundleId   string `json:"bundle_id"`
	PatchCount int    `json:"patch_count"`
}

//GetTPatchOfAPP
func GetPatchCountOfAPP() (ml []patchNumOfApp, err error) {
	o := orm.NewOrm()
	appTablename := new(TApp).TableName()
	patchTablename := new(TPatch).TableName()
	_, err = o.Raw("select " + appTablename + ".id as app_id,  " + appTablename + ".bundle_id as bundle_id, ifnull( app_sum.patch_count, 0) as patch_count  from  " + appTablename + " left join (SELECT count(*) as patch_count," + patchTablename + ".t_app_id FROM " + patchTablename + " group by " + patchTablename + ".t_app_id) app_sum on  " + appTablename + ".id = app_sum.t_app_id").QueryRows(&ml)
	if err != nil {
		return
	}
	return
}
